package com.ido.otaclient.nordic;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.ido.otaclient.StatusDownload;
import com.ido.otaclient.R;
import com.ido.otaclient.base.ApiConstant;
import com.ido.otaclient.base.BaseActivity;
import com.ido.otaclient.base.Constant;
import com.ido.otaclient.base.IDLog;
import com.ido.otaclient.dialog.WaitingDialog;
import com.ido.otaclient.dialog.WhiteConfirmDialog;
import com.ido.otaclient.module.Veneer;
import com.ido.otaclient.util.FileUtil;
import com.ido.otaclient.util.ResourceUtil;
import com.ido.otaclient.util.ToastUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class NordicActivity extends BaseActivity implements NordicContract.View{
    @BindView(R.id.title_text)
    TextView mTitleText;
    /**
     * 升级类型
     */
    @BindView(R.id.nordic_tab)
    RadioGroup mNordicTab;

    /**
     * 选择文件
     */
    @BindView(R.id.iv_choose)
    ImageButton mIvChoose;
    /**
     * 选择文件
     */
    @BindView(R.id.tv_choose_file)
    TextView mTvChooseFile;
    /**
     * 文件版本
     */
    @BindView(R.id.et_version)
    EditText mEtVersion;
    /**
     * 设备id
     */
    @BindView(R.id.et_device_id)
    TextView mEtDeviceId;
    /**
     * 升级类型为 Application
     */
    @BindView(R.id.tab_application)
    RadioButton mTabApplication;
    /**
     * 升级类型为bootloader
     */
    @BindView(R.id.tab_bootloader)
    RadioButton mTabBootloader;
    /**
     * 升级类型
     */
    private String mUpdateType = ApiConstant.UPDATE_TYPE_APPLICATION;

    /**
     * 选择文件的回调
     */
    private static final int REQUEST_CODE_FILE = 1000;


    /**
     * 已连接的单板
     */
    private List<Veneer> mVeneerList = new ArrayList<>();

    private static final String EXTRA_VENEER_LIST = "veneer_list";

    /**
     * 文件路径
     */
    private String mPath = "";

    private NordicContract.Presenter mPresenter;

    public static void startActivity(Activity activity,List<Veneer> veneerList){
        Intent intent = new Intent(activity,NordicActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_VENEER_LIST, (Serializable) veneerList);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent,Constant.REQUEST_CODE_LIST);
    }

    @Override
    protected void onCreateTask(Bundle savedInstanceState) {
        super.onCreateTask(savedInstanceState);
        setContentView(R.layout.activity_nordic);

        initTitle();
        initData();
        initListener();
    }

    private void initListener() {
        mNordicTab.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId){
                case R.id.tab_application:
                        mUpdateType = ApiConstant.UPDATE_TYPE_APPLICATION;
                    break;
                case R.id.tab_bootloader:
                        mUpdateType = ApiConstant.UPDATE_TYPE_BOOTLOADER;
                    break;
            }
        });
    }


    private void initData() {
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            mVeneerList = (List<Veneer>) bundle.getSerializable(EXTRA_VENEER_LIST);
            for(Veneer veneer : mVeneerList){
                IDLog.d(TAG, "initData: " + veneer.getIp());
                veneer.setDownloadStatus(StatusDownload.START.getCode());
            }
        }

        mPresenter = new NordicPresenter(this);
        mPresenter.initData();
        showMessage(ResourceUtil.getString(R.string.upload_confirm_config));

    }

    private void initTitle() {
        mTitleText.setText("Nordic升级");
    }

    @OnClick(R.id.title_leftBtn)
    public void back(View view){
        //ActivityCompat.finishAfterTransition(this);
        back();
    }

    @OnClick(R.id.btn_confirm)
    public void confirmUpdate(View view){
        //uploadAndConfirmFile();
        //确认配置 1、上传文件 2、确认配置
        mPresenter.uploadAndConfirmFile(mVeneerList);
    }





    @OnClick(R.id.iv_choose)
    public void chooseFile(View view){
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        String fileFolder = Constant.DIR_OUT_SDCRA;
        File file = new File(fileFolder);
        if (file.exists()) {
            //从指定目录下选择文件 这个现在不知道能不能实现 现在还是查询所有目录下的
            Uri uri = FileUtil.getUriFromFile(this, fileFolder);
            //Log.d(TAG, fileFolder + "," + uri.getPath());
            //intent.setDataAndType(uri, "*/*");
            intent.setType("*/*");
        } else {
            intent.setType("*/*");
        }
        startActivityForResult(intent, REQUEST_CODE_FILE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            // 用户未选择任何文件，直接返回
            return;
        }
        Uri uri = data.getData();
        mPresenter.showChooseFile(uri);
    }


    @Override
    public void showLoading() {
        WaitingDialog.showDialog(NordicActivity.this);
    }

    @Override
    public void hideLoading() {
        WaitingDialog.hideDialog();
    }

    @Override
    public void showMessage(String message) {
        ToastUtils.show(message);
    }

    @Override
    public void setChooseDrawable() {
        mIvChoose.setImageDrawable(ResourceUtil.getDrawable(R.drawable.ic_collection));
    }

    @Override
    public void showTvChooseFile(boolean isVisible) {
        mTvChooseFile.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setTvChooseFileName(String chooseFileName) {
        mTvChooseFile.setText(chooseFileName);
    }

    @Override
    public String getTvChooseFileName() {
        return mTvChooseFile.getText().toString();
    }

    @Override
    public String getChooseFileVersion() {
        return mEtVersion.getText().toString();
    }

    @Override
    public void setFilePath(String path) {
        mPath = path;
    }

    @Override
    public void setFileVersion(String version) {
        mEtVersion.setText(version);
    }

    @Override
    public String getFilePath() {
        return mPath;
    }

    @Override
    public void back() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_VENEER_LIST, (Serializable) mVeneerList);
        intent.putExtras(bundle);
        //intent.putStringArrayListExtra(EXTRA_VENEER_LIST,mVeneerList);
        setResult(Constant.REQUEST_CODE_LIST,intent);
        ActivityCompat.finishAfterTransition(this);
    }

    @Override
    public void setUpdateType(String updateType) {
        mUpdateType = updateType;
    }

    @Override
    public String getUpdateType() {
        return mUpdateType;
    }

    @Override
    public void showConfirmCancel() {
        WhiteConfirmDialog mWhiteConfirmDialog = WhiteConfirmDialog.newInstance(
                ResourceUtil.getString(R.string.upload_file_fail),ResourceUtil.getString(R.string.confirm),
                ResourceUtil.getString(R.string.cancel),true);
        mWhiteConfirmDialog.setOnConfirmListener(view -> {
            //重新下发固件
            mPresenter.uploadAndConfirmFile(mVeneerList);
            //uploadAndConfirmFile();
            mWhiteConfirmDialog.dismissAllowingStateLoss();
        });
        mWhiteConfirmDialog.setCancelListener(view -> {
            //取消弹框
            mWhiteConfirmDialog.dismissAllowingStateLoss();
            hideLoading();
        });

        mWhiteConfirmDialog.setCancelable(false);
        mWhiteConfirmDialog.show(getSupportFragmentManager());
    }

    @Override
    public void setVeneerList(List<Veneer> veneerList) {
        for(Veneer veneer : veneerList){
            IDLog.d(TAG, "setVeneerList: " + veneer.toString());
        }
        if(mVeneerList != null)
            veneerList.clear();
        mVeneerList.addAll(veneerList);
    }

    @Override
    public List<Veneer> getVeneerList() {
        for(Veneer veneer : mVeneerList){
            IDLog.d(TAG, "setVeneerList: " + veneer.toString());
        }
        return mVeneerList;
    }

    @Override
    public void checkApplication() {
        mTabApplication.setChecked(true);
    }

    @Override
    public void checkBootloader() {
        mTabBootloader.setChecked(true);
    }

    @Override
    public void setDeviceId(String deviceId) {
        mEtDeviceId.setText(deviceId);
    }

    @Override
    public String getDeviceId() {
        return mEtDeviceId.getText().toString();
    }

    @Override
    public void showConfirm(String failCount) {
        WhiteConfirmDialog mWhiteConfirmDialog = WhiteConfirmDialog.newInstance(
                ResourceUtil.getString(R.string.upload_file_fail_veneer_count,failCount),
                ResourceUtil.getString(R.string.confirm),
                ResourceUtil.getString(R.string.cancel),false);
        mWhiteConfirmDialog.setOnConfirmListener(view -> {
            //取消弹框
            mWhiteConfirmDialog.dismissAllowingStateLoss();
        });

        mWhiteConfirmDialog.setCancelable(false);
        mWhiteConfirmDialog.show(getSupportFragmentManager());
    }

    @Override
    public void setPresenter(@NonNull NordicContract.Presenter presenter) {
        mPresenter = presenter;
    }


}
